from django.http import HttpResponse, Http404, HttpResponseRedirect, \
    HttpResponseServerError, QueryDict
from django.shortcuts import render_to_response, get_object_or_404
from django.forms import ModelForm, models

import simdb.utils

urlmap = {}

for collection in simdb.utils.collections_list():
    urlmap[collection.__name__.lower()] = collection

def object_request(request, element, id):
    obj = get_object_or_404(urlmap[element], pk=id)

    if request.method == 'GET':
        response =  HttpResponse(obj.to_json(), status=200, 
                            mimetype='application/json')
        response['Content-Disposition'] = 'attachment; filename=%s%s.json' % (element, id)
        return response

    elif request.method == 'PUT':
        try:
            obj.from_json(request.raw_post_data)
        except:
            return HttpResponseServerError('Failed to update %s/%s' %
                                           (element, id) )
        return HttpResponse('Updated', status=200)
    elif request.method == 'DELETE':
        try:
            obj.delete()
            return HttpResponse('OK')
        except:
            return HttpResponseServerError('Failed to delete')

def collection_request(request, element):
    if not element in urlmap:
        raise Http404
    if request.method == 'GET':
        listing = {}
        listing['element'] = element
        listing['items'] = urlmap[element].objects.all()
        return render_to_response('simdb/browser/element_index.html', 
                                  {'listing': listing})
    elif request.method == 'POST':
        try:
            new_obj = urlmap[element]()
            new_obj.from_json(request.raw_post_data)
        except:
            return HttpResponseServerError('Failed to save\n%s' % request.POST)
        return HttpResponse('Created',status=201)

def elements_index(request):
    return render_to_response('simdb/browser/elements_index.html', 
                              {'listing': urlmap})
